import React, {Component} from 'react'
import Dimensions from 'react-dimensions'
import {fetchData} from '../../components/AjaxConsumer'
import {proviceCityData} from './proviceData'
import ModalTable from './modalTable'
import SelectUrl from '../../components/SelectUrl'
import {
    Form,
    Input,
    Tooltip,
    Icon,
    Cascader,
    Select,
    Row,
    Col,
    Checkbox,
    Button,
    message,
    Modal,
    Radio
} from 'antd';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const Option = Select.Option;


class RegistrationForm extends React.Component {
    state = {
        confirmDirty: false,
        loading: false,
        // visible:true,
        radioList: [],
        selectList:[],
        selectRemoteList: [],
        //selectUrl需要传入的参数
        urlForSelect: '/getSelectData',
        urlForCascadeSelect: '',
        dicCode: 'dicCode',
        dicName: 'dicName'
    };
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
                if (!err) {
                    this.setState({loading: true});
                    //将fieldsValue深拷贝给value
                    let values = {
                        ...fieldsValue,
                    };
                    //如果有城市联动(name为residence，则把值转换为后台需要的三个字段)
                    if(fieldsValue.residence != undefined){
                        values.proviceName = fieldsValue.residence[0];
                        values.cityName = fieldsValue.residence[1];
                        values.areaName = fieldsValue.residence[2];
                        delete values.residence;
                    }
                    //发送ajax 控制请求数据规则，无值的设为空
                    for (let item in values) {
                        if (!values[item]) {
                            values[item] = ''
                        }
                    }
                    //打印表单提交的值
                    console.log('Received values of form: ', values);
                    const options = {
                        url: 'deleteActionUrl',
                        type: 'post',
                        condition: {
                            values
                        }
                    };
                    fetchData(this, options, (res) => {
                        //回调函数
                        if (res.code == 1) {
                            message.success('操作成功');
                        }
                        setTimeout(() => {
                                this.setState({visible: false,loading: false})
                        }, 1000); //缓冲
                        
                    })
                }
            });
    };
    handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({
            confirmDirty: this.state.confirmDirty || !!value
        });
    };
    checkPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('Two passwords different!');
        } else {
            callback();
        }
    };
    checkConfirm = (rule, value, callback) => {
        const form = this.props.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], {force: true});
        }
        callback();
    };
    //每次输入都进行ajax获取数据
    handleSelectRemoteSearch = (value) => {
        console.log('onChangeSelectRemote2', value);
         if (value != ''){
            const options= {
                url: '/getSelectData2/'+value,
                condition:{},
                type: 'get', 
            };
            fetchData(this, options, (res) => {
                this.setState({ selectRemoteList: res.data })
            });
            
        }
    };
    //第一个级联框改变选种值的时候，发送ajax获取第二个级联框的下拉内容
    handleSelect1Change = (value) => {
        if (value != '' && value != undefined){
            //给selectUrl重新传参
            this.setState({ urlForCascadeSelect: '/getSelectData?'+Math.random() })
        } else {
            //清空select2的下拉值(当传入一个空的url时，selectUrl组件会自动清空下拉框)
            this.setState({ urlForCascadeSelect: ''})
        }
        //清空name为select2表单中缓存的key值 (notice:this step is very imoprtant!!)
        this.props.form.setFieldsValue({select2:''})
    };
    hanleIconSearchClick = () => {
        this.refs.modalTable.showModal();
    };
    //每次打开模态框，如果是需要空表单则清空下面相应需要清空的值，如果是有初始值，则在下面进行setState
    showModal = () => {
        //在这里初始化值
        this.setState({
            visible: true,
            radioList: [
                {radioKey:'radio1',radioShow:'选项一'},
                {radioKey:'radio2',radioShow:'选项二'},
                {radioKey:'radio3',radioShow:'选项三'},
                {radioKey:'radio4',radioShow:'选项四'},
                {radioKey:'radio5',radioShow:'选项五'},
                {radioKey:'radio6',radioShow:'选项六'},
                {radioKey:'radio7',radioShow:'选项七'},
                {radioKey:'radio8',radioShow:'选项八'},
                {radioKey:'radio9',radioShow:'选项九'},
            ],
            selectList:[
                {selectValue:'select1',SelectName:'下拉1'},
                {selectValue:'select2',SelectName:'下拉2'},
                {selectValue:'select3',SelectName:'下拉3'},
                {selectValue:'select4',SelectName:'下拉4'},
                {selectValue:'select5',SelectName:'下拉5'},
            ],
            selectRemoteList: [],
        });
        //如果表单没有拿到有初始值，则写上这一步
        this.props.form.resetFields(); //初始化表单
    };
    //获取弹出框内列表选中的值,将其放到name为inputTable的输入框中，并且让form拿到该值
    getTableData = (value) => {
        this.props.form.setFieldsValue({inputTable:value})
    };
    handleCancel = () => {
        this.setState({ visible: false });
        //取消的时候，不仅隐藏模态框，最好清空表单，防止下次表单内容还保存
        this.resetFrom();
    };
    resetFrom = () => {
        this.props.form.resetFields(); //初始化表单
        //初始化selectList下拉框的下拉内容
        this.setState({
            selectRemoteList: [],
            visible: false
        })
    };
    render() {
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6}
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14}
            }
        };

        /*
            如果 有弹出模态框表格 需要校验hasFeedback图标
            则需要使用此布局
        */
        const formItemLayout2 = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7}
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 16}
            }
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {span: 24,offset: 0},
                sm: {span: 24,offset: 10}
            }
        };
        //一行几个 （总宽度24,）
        const colNumber = 12;//一行2个
        return (
            <div>
                <Button type="primary" onClick={this.showModal}>
                    Open modal dialog
                </Button>

                <Modal
                    style={{top: '20px'}}
                    visible={this.state.visible}
                    title="自定义表单"
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    width={'850px'}
                    footer=''
                    maskClosable={false}>
                    <Form
                        onSubmit={this.handleSubmit}
                        style={{
                        backgroundColor: '#fff',
                        paddingTop: '20px',
                        paddingBottom: '20px'
                    }}>
                        <Row>
                            <Col span={colNumber}>
                                <FormItem {...formItemLayout} label="E-mail" hasFeedback>
                                    {getFieldDecorator('email', {
                                        initialValue:'123456789@qq.com',
                                        rules: [
                                            {
                                                type: 'email',
                                                message: '这不是一个有效的email!'
                                            }, {
                                                required: true, message: '请输入email!'
                                            }
                                        ]
                                    })(<Input disabled={true} />)}
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem {...formItemLayout} label="密码" hasFeedback>
                                    {getFieldDecorator('password', {
                                        initialValue: '',
                                        rules: [
                                            {
                                                // required: true, message: 'Please input your password!'
                                            }, {
                                                validator: this.checkConfirm
                                            }, {
                                                whitespace: true, message: "不能为空"
                                            }
                                        ]
                                    })(<Input type="password" />)}
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem {...formItemLayout} label="确认密码" hasFeedback>
                                    {getFieldDecorator('confirm', {
                                        initialValue: '',
                                        rules: [
                                            {
                                                // required: true, message: 'Please confirm your password!'
                                            }, {
                                                validator: this.checkPassword
                                            }, {
                                                whitespace: true, message: '不能为空'
                                            }
                                        ]
                                    })(<Input type="password" onBlur={this.handleConfirmBlur} />)}
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem
                                    {...formItemLayout}
                                    label='姓名'
                                    hasFeedback>
                                    {getFieldDecorator('nickname', {
                                        initialValue: '',
                                        rules: [{
                                                required: true, message: 'Please input your nickname!'
                                            }, {
                                                whitespace: true, message: '不能为空'
                                            }]
                                    })(<Input />)}
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem {...formItemLayout} label="省市区" hasFeedback>
                                    {getFieldDecorator('residence', {
                                        // initialValue: [
                                        //     'zhejiang', 'hangzhou', 'xihu'
                                        // ],
                                        rules: [
                                            {
                                                type: 'array',
                                                // required: true,
                                                message: 'Please select your habitual residence!'
                                            }
                                        ]
                                    })(
                                        <Cascader
                                            options={proviceCityData}
                                            placeholder="请选择"
                                            showSearch
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem {...formItemLayout} label="电话">
                                    {getFieldDecorator('phone', {
                                        initialValue: '18755555555',
                                        rules: [{
                                                pattern:/^1[34578]\d{9}$/, message:'填写正确的电话号码'
                                                // required: true, message: 'Please input your phone number!'
                                            }]
                                    })(<Input />)}
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem
                                    {...formItemLayout}
                                    label="数字"
                                >
                                    <Row gutter={8}>
                                        {getFieldDecorator('captcha', {
                                            initialValue: '',
                                            rules: [{
                                                    pattern:/^-?(?:[1-9][0-9]*|0)(?:.[0-9]+)?$/, message:'请输入数字'
                                                    // required: true, message: 'Please input the captcha you got!'
                                                }]
                                        })(<Input />)}
                                    </Row>
                                </FormItem>
                            </Col>
                            <Col span={colNumber} style={{height:'auto'}}>
                                <FormItem
                                    {...formItemLayout}
                                    label="单选按钮"
                                >
                                    <Row gutter={8}>
                                        {getFieldDecorator('radio', {
                                            initialValue: '',
                                            rules: [{
                                                    // required: true, message: 'Please input the captcha you got!'
                                                }]
                                        })(
                                            <RadioGroup >
                                                {
                                                    this.state.radioList.map((er,rIndex)=>{
                                                        return (
                                                            <Radio key={rIndex} value={er.radioKey}>{er.radioShow}</Radio>
                                                        )
                                                    })
                                                }
                                            </RadioGroup>
                                        )}
                                    </Row>
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem
                                    {...formItemLayout}
                                    label="下拉"
                                    hasFeedback
                                >
                                    <Row gutter={8}>
                                        {getFieldDecorator('selectUrl', {
                                            initialValue: '',
                                            rules: [
                                            //     { validator: this.checkSelectUrl }
                                                {required: true, message:'must select a item'}
                                            ],
                                        })(
                                            <SelectUrl url={this.state.urlForSelect}  dicCode={this.state.dicCode} dicName={this.state.dicName} isDisable={false} />
                                        )}
                                    </Row>
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem
                                    {...formItemLayout}
                                    label="远程动态下拉"
                                    hasFeedback
                                >
                                    <Row gutter={8}>
                                        {getFieldDecorator('selectRemote', {
                                            initialValue: '',
                                            rules: [{
                                                    // required: true, message: 'Please input the captcha you got!'
                                                }],
                                        })(
                                            <Select 
                                                placeholder="请选择" 
                                                showSearch 
                                                allowClear  
                                                onSearch={this.handleSelectRemoteSearch}
                                            >
                                                {
                                                     this.state.selectRemoteList.map((es,sIndex)=>{
                                                        return (
                                                            <Option key={sIndex} value={es.key}>{es.value}</Option>
                                                        )
                                                    })
                                                }
                                            </Select>
                                        )}
                                    </Row>
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem
                                    {...formItemLayout}
                                    label="级联下拉1"
                                >
                                    <Row gutter={8}>
                                        {getFieldDecorator('select1', {
                                            rules: [{
                                                    required: true, message: '中文提示！'
                                                }]
                                        })(
                                            <Select placeholder="请选择" showSearch allowClear onChange={this.handleSelect1Change} >
                                                {
                                                     this.state.selectList.map((es,sIndex)=>{
                                                        return (
                                                            <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                        )
                                                    })
                                                }
                                            </Select>
                                        )}
                                    </Row>
                                </FormItem>
                            </Col>
                            <Col span={colNumber}>
                                <FormItem
                                    {...formItemLayout}
                                    label="级联下拉2"
                                >
                                    <Row gutter={8}>
                                        {getFieldDecorator('select2', {
                                            rules: [{
                                                    required: true, message: '中文提示!'
                                                }]
                                        })(
                                           <SelectUrl url={this.state.urlForCascadeSelect}  dicCode={this.state.dicCode} dicName={this.state.dicName} isDisable={false} />
                                         )}
                                    </Row>
                                </FormItem>
                            </Col>
                            {/* 如果要使用hanFeedback图标校验，则需要改变formItemLayout2布局*/}
                            <Col span={colNumber}>
                                    <Row gutter={0}>
                                        <Col span={21}>
                                        <FormItem
                                            {...formItemLayout2}
                                                label="弹出列表"
                                                hasFeedback
                                            >
                                            {getFieldDecorator('inputTable', {
                                                rules: [{
                                                        required: true, message: 'Please input the captcha you got!'
                                                    }]
                                            })(
                                                <Input />
                                            )}
                                            </FormItem>
                                        </Col>
                                        <Col span={3} style={{paddingTop:'6px',boxSizing:'border-box'}}>
                                            <Icon type="search" style={{cursor:'pointer'}} onClick={this.hanleIconSearchClick} />
                                        </Col>
                                    </Row>
                            </Col>
                            <Col span={24}>
                                <FormItem {...tailFormItemLayout}>
                                    <Button type="primary" htmlType="submit" size="large">{this.state.loading?'提交中...':'确定'}</Button>
                                    <Button
                                        type="default"
                                        style={{marginLeft: '50px'}}
                                        size="large"
                                        onClick={this.resetFrom}
                                    >
                                        取消
                                    </Button>
                                </FormItem>
                            </Col>

                        </Row>
                    </Form>
                </Modal>
                <ModalTable getTableData={this.getTableData} ref='modalTable' />
            </div>
        );
    }
}

export default Form.create()(RegistrationForm);
